<template>
  <a-modal title="修改手机号" title-align="start" v-model:visible="showvisible" @cancel="showvisible = false" :width="500">
    <a-form :model="form" auto-label-width :rules="rules" ref="formRef">
      <a-form-item label="请输入手机号：" field="mobile">
        <a-input v-model="form.mobile" />
      </a-form-item>
      <a-form-item label="请输入验证码：" field="verifyCode">
        <a-space>
          <a-input v-model="form.verifyCode" />
          <a-button type="primary" @click="getCode" :disabled="countDownNum != 60">{{ countDownNum != 60 ? `${countDownNum}秒后重新发送` : '获取验证码' }}</a-button>
        </a-space>
      </a-form-item>
    </a-form>

    <template #footer class="modal-footer">
      <a-button @click="showvisible = false">取消</a-button>
      <a-button type="primary" :loading="submitLoading" @click="submit">确认</a-button>
    </template>
  </a-modal>
</template>

<script lang="ts" setup>
  import { computed, ref } from 'vue'
  import { updateUserMobile } from '@/api/system'
  import { Message } from '@arco-design/web-vue'

  let props = defineProps(['modelValue', 'id'])
  let emits = defineEmits(['update:modelValue', 'save'])
  const form: any = ref({})
  const formRef = ref()
  const rules: any = ref({
    mobile: [{ required: true, message: '请输入手机号' }],
    verifyCode: [{ required: true, message: '请输入验证码' }],
  })
  let submitLoading = ref(false)
  let countDownNum = ref(60)
  let showvisible: any = computed({
    set(val) {
      emits('update:modelValue', val)
    },
    get() {
      return props.modelValue
    },
  })

  const getCode = async () => {
    if (!form.value.mobile) return Message.error('请输入手机号')
    let timer = setInterval(() => {
      countDownNum.value == countDownNum.value--
      if (countDownNum.value <= 0) {
        clearInterval(timer)
        countDownNum.value = 60
      }
    }, 1000)
  }

  const submit = async () => {
    const valid = await formRef.value.validate()
    if (!valid) {
      try {
        submitLoading.value = true
        form.value.id = props.id
        await updateUserMobile(form.value)
        Message.success('手机号修改成功')
        showvisible.value = false
        emits('save')
      } catch (error) {}
      submitLoading.value = false
    }
  }
</script>

<style lang="less" scoped></style>
